package com.laiyima.zhongjiang.linghuilv.demo.home;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.king.zxing.util.CodeUtils;
import com.laiyima.zhongjiang.linghuilv.demo.R;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class ExtensionActivity extends SwipeBackActivity implements View.OnClickListener {
    private ImageView show_QR_code;
    private LinearLayout backImageView;
    private Button save_tp;
    private int ectCode;
    private String TAG="ExtensionActivity";
    String ext_Url;
    private Bitmap qrCodeBitmap,image;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };

    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值
    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                // getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }
    public static void verifyStoragePermissions(Activity activity) {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_extension);
        backImageView= (LinearLayout) findViewById(R.id.elect_back);
        show_QR_code= (ImageView) findViewById(R.id.show_QR_code);
        save_tp= (Button) findViewById(R.id.save_pictures);

        backImageView.setOnClickListener(this);
        save_tp.setOnClickListener(this);
        intView();
        String url=ext_Url;
        setStatusBar();
        verifyStoragePermissions(this);


    }

    private void intView() {
        SharedPreferences sharedPreferences =getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params1 = new RequestParams("http://zljl.laiima.com/index.php?s=/api/Userlist/ageneralize");
        //需要带入的参数
        params1.addBodyParameter("uid", userID);
         x.http().post(params1, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    ectCode = jsonObject.optInt("code", 0);
                    ext_Url=jsonObject.optString("url","");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (ectCode == 200) {
                    //生成二维码
                    Bitmap portrait = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
                    qrCodeBitmap = CodeUtils.createQRCode(ext_Url,600,portrait);
                    show_QR_code.setImageBitmap(qrCodeBitmap);
                }
                if (ectCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
//                        Intent Nameintent=new Intent(HomeActivity.this,NameActivity.class);
//                        startActivity(Nameintent);
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {

            }
        });


    }

    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.elect_back:
                this.finish();
                break;
            case R.id.save_pictures:
                image = ((BitmapDrawable)show_QR_code.getDrawable()).getBitmap();
                mysaveImageToGallery(this,qrCodeBitmap);
                Toast.makeText(getBaseContext().getApplicationContext(), "二维码保存成功", Toast.LENGTH_SHORT).show();
                break;
        }

    }


    /**
     * 保存图片到相册
     */
    public static void mysaveImageToGallery(Context context, Bitmap bmp) {
        String fileName = System.currentTimeMillis() + ".jpg";
       // String filePath = FileUtils.getFilePath(context, "/pictures/qrcode/");
        // 首先保存图片
        File appDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsoluteFile();;
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 0, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e){

        }

        // 其次把文件插入到系统图库
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
    }
}
